import { baseURL } from '@/common/baseconfig.js'
import { Toast, removeProperty } from '@/utils/tools.js';
import { isEmpty, urlEncode } from '@/libs/fn/verify.js'
import { Jump } from '@/libs/fn/jump.js'
import store from '@/store/index.js'
import cookie from '@/utils/auth.js'

const waitingList = []; // 等待请求队列
const excutingList = []; // 执行队列
const limit = 1; // 最大请求数

const excuteWaitingList = () => {
	const func = waitingList[0];
	if (typeof func === 'function') {
		func();
	}
	waitingList.splice(0, 1);
};

const requestPromise = ({
	resolve,
	reject,
	url,
	method,
	params,
	data,
	mask,
	timeout,
	showToast,
	callback,
	headers
}) => {
	params = removeProperty(params);
	let _url = url;
	//params传值方式  默认拼接到请求后缀
	if (!isEmpty(params)) {
		_url = `${_url}${urlEncode(params)}`
	}
	let header = {
		'Token': cookie.get('Token'),
		...headers
	};
	let success = false;
	const baseUrl = baseURL;
	if (mask) {
		// #ifdef APP-PLUS
		plus.nativeUI.showWaiting();
		// #endif
		// #ifndef APP-PLUS
		uni.showLoading({
			mask: true,
			title: '加载中'
		})
		// #endif
	}
	const requestTask = uni.request({
		url: _url.startsWith('https://') ? _url : baseUrl + _url, //仅为示例，并非真实接口地址。
		method: method ? method.toUpperCase() : '',
		data: data,
		header: header,
		timeout: timeout,
		success: ({ data, statusCode }) => {
			if (statusCode === 200) {
				const { success, msg, code } = data;
				const dataType = {
					list: [],
					pageCount: 0,
				}
				//错误时  默认打印提示
				if (!success) {
					if (showToast) Toast(msg)
					resolve(data);
				}
				if (code == 'notlogin') {
					store.commit('user/REMOVE_TOKEN')
					let noewRoute = '';
					try {
						noewRoute = getCurrentPages()[0]['route'];
					} catch (e) {
						console.log(e)
					}
					if (noewRoute !== 'pages/login/login') {
						Jump({
							url: '/pages/login/login',
							mode: 3
						});
						Toast(msg)
					}
				}
				resolve(data);
			} else {
				errorHandler(statusCode);
				Toast(`${data.status}:${data.title}`)
				// let errData={
				// 	success:false,
				// 	msg:data.title,
				// 	code:data.status
				// }
				// reject(errData);
			}
		},
		fail(e) {
			errorHandler('ERR_CONNECTION_TIMED_OUT')
			return reject(e)
		},
		complete() {
			if (mask) {
				// #ifdef APP-PLUS
				plus.nativeUI.closeWaiting();
				// #endif
				// #ifndef APP-PLUS
				uni.hideLoading();
				// #endif
			}
			if (success) {
				resolve(true);
			} else {
				resolve(false);
			}
			let index = excutingList.indexOf(requestTask);
			excutingList.splice(index, 1);
			if (typeof callback === 'function') {
				callback();
			}
			excuteWaitingList();
		},
	});
	excutingList.push(requestTask);
}

export default function ajaxRequest({
	url,
	method = 'get',
	params,
	data,
	timeout = 60000,
	mask = false,
	showToast=false,
	headers,
}) {
	const promiseObj = new Promise((resolve, reject) => {
		console.log('excutingList===>',excutingList)
		if (excutingList.length > limit) {
			waitingList.push((callBack) => {
				requestPromise({
					resolve,
					reject,
					url,
					method,
					params,
					data,
					timeout,
					headers,
					showToast,
					callBack
				})
			});
		} else {
			requestPromise({ resolve, reject, url, method, params,showToast,data, timeout, headers })
		}
	});
	return promiseObj;
}

const clearAllRequest = () => {
	excutingList.map((item) => {
		if (item && item.abort) {
			item.abort();
		}
	});
	waitingList.length = 0;
	excutingList.length = 0;
}

function errorHandler(statusCode) {
	let errorCode;
	if (statusCode) {
		errorCode = statusCode
	} else {
		// errorCode = error.code;
	}
	const errorHint = {
		'ERR_CONNECTION_TIMED_OUT': '请求超时，请稍后再试',
		'request:fail timeout': '请求超时，请稍后再试',
		"ERR_NETWORK": '网络繁忙，请稍后再试',
		"ECONNABORTED": '请求超时',
		'400': '请求错误',
		'401': '未授权',
		'403': '拒绝访问',
		'404': '请求地址出错',
		'408': '请求超时',
		'500': '服务器内部错误',
		'501': '服务未实现',
		'502': '网关错误',
		'503': '服务不可用',
		'504': '网关超时',
		'505': 'HTTP版本不受支持',
	} [errorCode] || '网络繁忙,请稍后再试';
	// //错误页面
	// Jump({
	// 	url: '/pages/error',
	// 	params: {
	// 		msg: errorHint
	// 	}
	// })
	// Toast(errorHint);
}